import { Form, Input, Button, message } from "antd";
import React, { useEffect, useState } from "react";
import style from "./style.less"
import { RegisterInfo } from "../../interface/account";
import { registerAccount } from "../../service/account";
import { useNavigate } from "react-router-dom";
import { ISendCode } from "../../interface/confirmCode";
import { checkCode, senCode } from "../../service/code";

export default function Register() {
  const navigate = useNavigate()
  const [password, setPassword] = useState<string>('')
  const [confirm, setConfirm] = useState<string>('')
  const [samePassword, setSamePassword] = useState<boolean>(true)
  const [safePassword, setSafePassword] = useState<boolean>(true)
  const [sentCode, setSentCode] = useState<boolean>(false)
  const [time, setTime] = useState<string>('60')
  const [account, setAccount] = useState<string>()

  useEffect(() => {
    let timer = 59
    const countTime = setInterval(() => {
      setTime((timer--).toString())
      return () => {
        setTime("59")
      }
    }, 1000)
    if (sentCode) {
      setTimeout(() => {
        setSentCode(false)
        clearInterval(countTime)
      }, 60000)
      message.success("验证码发送成功，三分钟内有效")
    } else {
      clearInterval(countTime)
    }
    return () => {
      clearInterval(countTime)
    }
  }, [sentCode])

  async function registerNewAccount(registerInfo: RegisterInfo) {
    const registerResult = await registerAccount(registerInfo)
    if (registerResult.stat === 'ok') {
      alert("注册成功，点击确定返回登录页面")
      navigate("/login")
    } else {
      message.error(registerResult.msg)
    }
  }

  async function handleRegister(params: RegisterInfo) {
    const data = await checkCode({ account: account!, code: params.confirmCode })
    if (data.stat === 'ok') {
      registerNewAccount(params)
    } else {
      message.error(data.msg)
    }
  }

  async function sendCode(params: ISendCode) {
    // 电话号码正则验证
    if (/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(params.account)) {
      const data = await senCode(params)
      if (data.stat === 'ok') {
        setSentCode(true)
      } else {
        message.error(data.msg)
      }
    } else {
      message.error("请填入正确的电话号码")
    }

  }

  function checkSamePassword(confirmPassword: string) {
    if (confirmPassword !== password) {
      setSamePassword(false)
    } else {
      setSamePassword(true)
    }
  }

  function checkSafePassword(password: string) {
    if (password === '' || !!password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/)) {
      setSafePassword(true)
    } else {
      setSafePassword(false)
    }
  }



  return (
    <React.Fragment>
      <div className={style.content}>
        <Form
          className={style.inputList}
          onFinish={(value) => {
            handleRegister({
              ...value,
              account: value.telephone.toString()
            })
          }}>
          <Form.Item
            className={style.inputPart}
            label="设置昵称:"
            name={"nickname"}>
            <Input
              placeholder="昵称"
              className={style.inputBox}
            />
          </Form.Item>
          <Form.Item
            className={style.inputPart}
            label="手机号码:"
            name={"telephone"}
          >
            <Input
              onChange={(value) => {
                setAccount(value.target.value)
              }}
              type={"tel"}
              maxLength={11}
              className={style.inputBox}
            />
          </Form.Item>
          <Form.Item
            className={style.inputPart}
            label="设置密码"
            name={"setPassword"}
          >
            <Input
              placeholder="八位以上，包含大、小写字母和数字"
              value={password}
              onBlur={(value) => {
                setPassword(value.target.value);
                checkSafePassword(value.target.value)
              }}
              type={"password"}
              className={style.inputBox}
            />
          </Form.Item>
          <Form.Item
            className={style.inputPart}
            label="确认密码:"
            name={"confirmPassword"}
          >
            <Input
              placeholder="请再次输入密码"
              value={confirm}
              onBlur={(value) => {
                setConfirm(value.target.value);
                checkSamePassword(value.target.value)
              }}
              type={"password"}
              className={style.inputBox}
            />
          </Form.Item>
          {safePassword ? <></> : <div
            className={

              style.passwordTip
            }
          >
            密码必须大于8位，小于十六位，包含大写字母，小写字母和数字
          </div>}
          {samePassword ? <></> : <div
            className={
              style.passwordTip
            }
          >
            两次输入的密码不同，请重新输入
          </div>}
          <Button
            disabled={(!account) || (sentCode)}
            onClick={() => {
              sendCode({ account: account! })
            }}
            type={"primary"}
            className={style.sendCode}
          >
            {sentCode ? `${time}s后可再次发送` : "发送验证码"}
          </Button>
          <Form.Item
            className={style.inputPart}
            label="验证码"
            name={"confirmCode"}
          >
            <Input
              className={style.inputBox}
            />
          </Form.Item>
          <Form.Item>
            <Button
              disabled={(!(samePassword || safePassword)) || (password === '')}
              className={style.submit}
              htmlType={"submit"}
              type={"primary"}
            >
              注册
            </Button>
          </Form.Item>
        </Form>
      </div>
    </React.Fragment>
  )
}